<template>
	<el-card class="box-card">
		<el-form ref="queryForm" :model="query" :inline="true">
			<el-form-item label="权限名称" prop="name">
				<el-input v-model="query.name" placeholder="请输入权限名称" clearable @keyup.enter.native="handleQuery(1)" />
			</el-form-item>
      <el-form-item label="菜单名称" prop="menuId">
        <el-select v-model="query.menuId" placeholder="全部" clearable @change="handleQuery(1)">
          <el-option
            v-for="dict in moduleList"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
			<el-form-item label="状态" prop="inuse">
				<el-select v-model="query.inuse" placeholder="全部" clearable @change="handleQuery(1)">
					<el-option label="启用" :value="1" />
					<el-option label="禁用" :value="0" />
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" @click="handleQuery(1)">搜索</el-button>
				<el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb20">
			<el-col :span="1.5">
				<el-button v-hasPermi="['/permission/save']" type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
        <!-- <el-button :disabled="!ids.length" type="danger" icon="el-icon-delete" @click="handleDelete()">删除</el-button> -->
			</el-col>
		</el-row>

		<el-card class="box-card">
			<el-table v-loading="listLoading" :data="dataList" border @selection-change="handleSelectionChange">
				<!-- <el-table-column type="selection" width="50" align="center" /> -->
				<el-table-column prop="name" label="权限名称" show-overflow-tooltip width="200" />
				<el-table-column prop="menuName" label="菜单名称" show-overflow-tooltip width="200" />
				<el-table-column label="权限级别">
					<template slot-scope="{row}">
						<div class="flex-center">
              <span>{{ row.level===1?'系统权限':'普通权限' }}</span>
              <el-tooltip class="item" effect="dark" placement="top">
                <div slot="content">系统权限不能删除和更改状态<br/>若想更改,编辑按钮级别</div>
                <i class="icon-warn el-icon-warning"></i>
              </el-tooltip>
            </div>
					</template>
				</el-table-column>
				<el-table-column prop="url" label="权限路径" show-overflow-tooltip width="240" />
				<!-- <el-table-column prop="about" label="描述" show-overflow-tooltip width="320" /> -->
				<el-table-column label="状态" width="80">
					<template slot-scope="{row}">
						<el-switch v-hasPermi="['/permission/update']" :disabled="row.level===1" :value="row.inuse" :active-value="1" :inactive-value="0" @change="switchChange($event, row.id)" />
					</template>
				</el-table-column>
				<el-table-column label="创建时间" align="center" prop="ctime">
					<template slot-scope="scope">
						<span>{{ scope.row.ctime | parseTime }}</span>
					</template>
				</el-table-column>
				<el-table-column label="操作" align="center" class-name="small-padding fixed-width">
					<template slot-scope="{row}">
						<el-button v-hasPermi="['/permission/update']" type="text" @click="handleUpdate(row.id)">编辑</el-button>
						<el-button v-if="row.level!==1" v-hasPermi="['/permission/delete/*']" type="text" @click="handleDelete(row.id)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>

			<pagination v-show="total>0" :total="total" :page.sync="query.pageNum" :limit.sync="query.pageSize" @pagination="handleQuery" />
		</el-card>

		<!-- 添加或修改权限 -->
		<el-dialog :title="(formModel.id?'编辑':'新增')+'权限'" :visible.sync="formVisible" width="680px" append-to-body>
			<el-form ref="formModel" :model="formModel" :rules="formRules" label-width="80px">
				<el-row>
					<el-col :span="12">
						<el-form-item label="权限名称" prop="name">
							<el-input v-model="formModel.name" placeholder="请输入权限名称" maxlength="20" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="模块" prop="menuId">
              <el-select v-model="formModel.menuId" placeholder="请选择模块" clearable>
                <el-option
                  v-for="dict in moduleList"
                  :key="dict.id"
                  :label="dict.name"
                  :value="dict.id"
                />
              </el-select>
						</el-form-item>
					</el-col>
				</el-row>
        <el-row>
					<el-col :span="12">
						<el-form-item label="权限级别" prop="level">
              <el-radio-group v-model="formModel.level">
                <el-radio-button :label="1">系统权限</el-radio-button>
                <el-radio-button :label="2">普通权限</el-radio-button>
              </el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="状态">
							<el-switch :disabled="formModel.level===1" v-model="formModel.inuse" :active-value="1" :inactive-value="0" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
						<el-form-item label="权限路径" prop="url">
							<el-input v-model="formModel.url" placeholder="请输入权限路径" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="24">
            <el-form-item label="描述">
              <el-input v-model="formModel.about" type="textarea" placeholder="请输入描述内容"></el-input>
            </el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click="formVisible=!formVisible;reset;">取 消</el-button>
				<el-button :loading="submitLoading" type="primary" @click="submitForm">确 定</el-button>
			</div>
		</el-dialog>
	</el-card>
</template>

<script>
import { permissionListPage, permissionGetId, permissionDeleteId,
  permissionDeleteBatch, permissionSave, permissionUpdate, getSecondMenus } from '@/api/system/auth'

export default {
  data () {
    return {
      // 列表数据
      query: {
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      dataList: null,
      listLoading: false,
      ids: [],
      // 新增/编辑权限
      formVisible: false,
      submitLoading: false,
      formModel: {
        inuse: 1,
        level: 2
      },
      formRules: {
        name: [
          { required: true, message: "权限名称不能为空", trigger: "blur" }
        ],
        url: [
          { required: true, message: "资源路径不能为空", trigger: "blur" }
        ],
        menuId: [
          { required: true, message: "请选择模块id", trigger: "blur" }
        ],
      },
      moduleList: []
    }
  },
  created () {
    this.handleQuery()
    this.getModuleList()
  },
  methods: {
    getModuleList () {
      getSecondMenus().then(res => {
        this.moduleList = res.data
      })
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map(item => item.id)
    },
    handleQuery (pageNum) {
      if (pageNum===1) this.query.pageNum = 1
      this.listLoading = true
      permissionListPage(this.query).then(res => {
        const { records, total } = res.data
        this.dataList = records
        this.total = total
        this.listLoading = false
      }).catch(err => {
        if (err.code === -103) {
          this.$router.push('/403')
        }
        this.listLoading = false
      })
    },
    resetQuery () {
      this.resetForm('queryForm')
      this.handleQuery(1)
    },
    handleAdd () {
      this.reset()
      this.formVisible = !this.formVisible
    },
    handleUpdate (id) {
      this.handleAdd()
      permissionGetId(id).then(res => {
        this.formModel = { ...res.data }
      })
    },
    handleDelete (id) {
      if (id) {
        this.$confirm(`请确认是否要删除该权限?`, { type: 'warning' }).then(() => {
          permissionDeleteId(id).then(() => {
            this.$message.success('删除成功')
            this.handleQuery()
          })
        })
      } else {
        this.$confirm(`请确认是否要删除该批权限?`, { type: 'warning' }).then(() => {
          permissionDeleteBatch(this.ids).then(() => {
            this.$message.success('删除成功')
            this.handleQuery()
          })
        })
      }
    },
    // 新增/编辑
    submitForm () {
      this.submitLoading = true
      this.$refs["formModel"].validate(async valid => {
        if (valid) {
          try {
            if (this.formModel.id) {
              await permissionUpdate(this.formModel)
              this.$message.success('修改成功')
            } else {
              await permissionSave(this.formModel)
              this.$message.success('新增成功')
            }
            this.formVisible = !this.formVisible
            this.handleQuery()
            this.submitLoading = false
          } catch (error) {
            this.submitLoading = false
          }
        } else {
          this.submitLoading = false
        }
      })
    },
    // 表单重置
    reset () {
      this.formModel = {
        inuse: 1,
        level: 2
      }
      this.resetForm("formModel")
    },
    // 状态变更
    switchChange (inuse, id) {
      this.$confirm(`请确认是否要${inuse === 0 ? '禁用' : '启用'}该权限?`, { type: 'warning' }).then(() => {
        permissionUpdate({ id, inuse }).then(() => {
          this.handleQuery()
        })
      })
    }
  }
}
</script>

<style lang="scss">
.flex-center{
  display: flex;
  align-items: center;
  .icon-warn{
    margin-left: 6px;
    font-size: 16px;
    color: #bbb;
  }
}
</style>
